package com.hedl.practice.diyJava.encryptionandsecurity.asymmetric_encryption_algorithm.tmp;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;

public class Person {
    private String name;

    //私钥
    private PrivateKey sk;
    //公钥
    private PublicKey pk;

    public Person(String name) throws NoSuchAlgorithmException {
        this.name = name;

        //生成公钥/私钥对
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
        kpGen.initialize(1024);
        KeyPair kp = kpGen.generateKeyPair();
        this.sk = kp.getPrivate();
        this.pk = kp.getPublic();
    }

    //把私钥导出为字节
    public byte[] getPrivateKey(){
        return this.sk.getEncoded();
    }

    //把公钥导出为字节
    public byte[] getPublicKey(){
        return this.pk.getEncoded();
    }

    //用公钥加密
    public  byte[] encrypt(byte[] message){
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE,this.pk);
            return cipher.doFinal(message);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    //用私钥解密
    public byte[] decrypt(byte[] input){
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE,this.sk);
            return cipher.doFinal(input);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }
}
